//
//  TJTaskDetailController.m
//  BaoDian
//
//  Created by mac on 2024/7/28.
//

#import "TJTaskDetailController.h"
#import "TJTaskDetailCell.h"
#import "TJEmptyDataHandler.h"
#import "TJModifyPOIController.h"
#import "TJPhotosTool.h"
#import "TJUrlDataModel.h"
#import <DouyinOpenSDK/DouyinOpenSDKShare.h>
#import "TJVideoPlayController.h"

@interface TJTaskDetailController ()

@property (nonatomic, strong) TJEmptyDataHandler *emptyDataHandler;

@property (nonatomic, strong) CAShapeLayer *topShapeLayer;
@property (nonatomic, strong) CAShapeLayer *bottomShapeLayer;
@property (nonatomic, strong) NSMutableArray *datas;
@property (nonatomic, weak) UILabel *subTitleLabel;

@end

@implementation TJTaskDetailController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth - 32, 85)];
    
    UILabel *titleLabel = [UILabel lableWithSuperView:headerView font:UIFontBoldMake(22) color:UIColor.whiteColor title:nil textAlignment:NSTextAlignmentLeft];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(10);
        make.left.offset(0);
    }];
    
    UILabel *subTitleLabel = [UILabel lableWithSuperView:headerView font:UIFontMake(12) color:UIColor.whiteColor title:@"今日剩余打卡次数：--次" textAlignment:NSTextAlignmentLeft];
    subTitleLabel.alpha = 0.8;
    [subTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(titleLabel.mas_bottom).offset(8);
        make.left.equalTo(titleLabel);
        make.right.inset(leftRightMargin);
    }];
    
    if (_model.taskStatus.intValue == 3) {
        titleLabel.text = @"任务进行中...";
    } else if (_model.taskStatus.intValue == 5 || _model.taskStatus.intValue == 4) {
        titleLabel.text = @"任务已结束...";
    }  else {
        titleLabel.text = @"任务未启动...";
    }
    
    self.tableView.tableHeaderView = headerView;
    [self.tableView registerClass:TJTaskDetailCell.class forCellReuseIdentifier:@"TJTaskDetailCell"];
    self.tableView.separatorColor = UIColorMake(0x2A2B31);
    self.tableView.rowHeight = 210;
    [self.tableView setContentInset:UIEdgeInsetsMake(0, 0, TabbarSafeBottomMargin, 0)];
    self.tableView.backgroundColor = UIColor.clearColor;
    self.tableView.showsVerticalScrollIndicator = NO;
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(KNavBarHight);
        make.left.right.inset(16);
        make.bottom.offset(0);
    }];
    
    _emptyDataHandler = [TJEmptyDataHandler emptyDataHandleWithScrollView:self.tableView configuration:^TJEmptyDataType(TJEmptyDataModel * _Nonnull dataModel) {
        dataModel.text = @"你暂时还没有创建分组";
        dataModel.iconName = @"clockInRecardEmpty";
        return TJEmptyDataTypeBase;
    }];
    _subTitleLabel = subTitleLabel;
    
    [self loadData];
}
 
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.datas.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    TJTaskDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TJTaskDetailCell" forIndexPath:indexPath];
    TJTaskModel *model = self.datas[indexPath.row];
    cell.model = model;
    if (indexPath.row == 0) {
        cell.layer.mask = [self topShapeLayerWithView:cell];
    } else if (indexPath.row == [tableView numberOfRowsInSection:indexPath.section] - 1) {
        cell.layer.mask = [self bottomShapeLayerWithView:cell];
    } else {
        cell.layer.mask = nil;
    }
    
    TJWeakify(self)
    [cell setDidClickModifyButtonBlock:^{
        TJModifyPOIController *modifyPOIController = [[TJModifyPOIController alloc] init];
        modifyPOIController.clockPlanId = model.Id;
        [modifyPOIController setComplete:^(NSString * _Nonnull poi) {
            model.poiInfo = poi;
            [weakself.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
        }];
        [weakself presentViewController:modifyPOIController animated:NO completion:nil];
    }];
    
    [cell setDidClickClockInButtonBlock:^{
        [weakself clockInWithModel:model];
    }];
    
    [cell setTapCoverImageViewBlock:^(UIImage *coverImage){
        TJVideoPlayController *videoPlayController = [[TJVideoPlayController alloc] init];
        videoPlayController.url = model.videoUrl;
        videoPlayController.coverImage = coverImage;
        [weakself presentViewController:videoPlayController animated:YES completion:nil];
    }];
    
    return cell;
}

- (void)downloadWithModel:(TJTaskModel *)model {
    
    TJUrlDataModel *dataModel = [[TJUrlDataModel alloc] init];
    dataModel.url = model.videoUrl;
    
    NSString *localPath = [NSString stringWithFormat:@"%@.%@",  model.videoUrl.md5,  model.videoUrl.pathExtension].tj_cachePath;
    if ([[NSFileManager defaultManager] fileExistsAtPath:localPath]) {
        [TJPhotosTool saveVideoToPhotoLibrary:[NSURL fileURLWithPath:localPath] completion:^(NSError * _Nonnull error, NSString * _Nonnull localIdentifier) {
            if (error) {
                return;
            }
            dataModel.localPath = localPath;
            dataModel.localIdentifier = localIdentifier;
            [dataModel bg_saveOrUpdate];
            [self sendToDouYin:localIdentifier taskModel:model];
        }];
    } else {
        [TJHUD showLoadingInView:self.view text:@"下载中"];
        TJDownloadFileWithUrl(model.videoUrl, ^(CGFloat value) {
            [TJHUD updateHudText:[NSString stringWithFormat:@"下载中%.2f%%", value * 100]];
        }, ^NSURL * _Nonnull{
            return [NSURL fileURLWithPath:localPath];
        }, ^(NSError * _Nullable error) {
            if (error) {
                [TJHUD showSucceedMessage:@"下载视频失败"];
                return;
            }
            
            [TJHUD hiddenLoading];
            
            dataModel.localPath = localPath;
            [dataModel bg_saveOrUpdate];
            
            [TJPhotosTool saveVideoToPhotoLibrary:[NSURL fileURLWithPath:localPath] completion:^(NSError * _Nonnull error, NSString * _Nonnull localIdentifier) {
                if (error) {
                    return;
                }
                dataModel.localIdentifier = localIdentifier;
                [dataModel bg_saveOrUpdate];
                [self sendToDouYin:localIdentifier taskModel:model];
            }];
        });
    }
}

- (void)sendToDouYin:(NSString *)localIdentifier taskModel:(TJTaskModel *)taskModel {
    
    dispatch_async_main_queue(^{
        
        [TJMinePresent getClockPlanShareIdWithId:taskModel.Id complete:^(NSString * _Nonnull shareId, NSError * _Nullable error) {
            if (shareId) {
                
                DouyinOpenSDKShareRequest *req = [[DouyinOpenSDKShareRequest alloc] init];
                req.mediaType = DouyinOpenSDKShareMediaTypeVideo; // 分享的资源为纯视频类型
                req.localIdentifiers = @[localIdentifier]; // NSArray<NSString *> * （系统相册的本地标识符）
                req.landedPageType = DouyinOpenSDKLandedPagePublish; // 发布页面（需要抖音14.7版本以上）
                req.publishStory = NO; // 是否转发到日常,设置为YES的时使用转发到日常能力，设置为NO时使用投稿能力
                req.title = [DouyinOpenSDKShareTitle new];
                req.title.text = taskModel.text; // 正文
                req.state = shareId;
                
                
                NSLog(@"req.localIdentifiers = %@", req.localIdentifiers);
                NSLog(@"req.state = %@", req.state);
                NSLog(@"req.title.text = %@", req.title.text);
                
             
                if ([taskModel.packType intValue] == 0) {//无挂载

                } else if ([taskModel.packType intValue] == 1) {//poi
                    req.poiID = taskModel.poiId;
                } else if ([taskModel.packType intValue] == 2) {
                    
                    // 设置分享携带小程序（小程序与应用必须为同一主体）
                    NSMutableDictionary *dict = @{}.mutableCopy;
                    [dict setValue:taskModel.microAppId forKey:@"identifier"];
                    [dict setValue:taskModel.microAppTitle forKey:@"title"];
                    [dict setValue:taskModel.microAppUrl forKey:@"startPageURL"];
                    // 小程序，在分享的视频右下角显示抖音小程序入口, 非必须属性
                    req.extraInfo = @{@"mpInfo" : dict.copy};
                }
                
                [req sendShareRequestWithCompleteBlock:^(DouyinOpenSDKShareResponse * _Nonnull respond) {
                    NSLog(@"respond.errCode = %ld", respond.errCode);
                    NSLog(@"respond.errString = %@", respond.errString);
                    NSLog(@"respond.state = %@", respond.state);
                    NSLog(@"respond.state = %ld", respond.shareState);
                    
                    [TJMinePresent updateClockPlanWithId:taskModel.Id status:toString(@(respond.errCode)) complete:^(NSError * _Nullable error) {
                        if (error) {
                            return;
                        }
                        
                        [self loadData];
                        [TJHUD showMessage:@"发布成功"];
                    }];
                }];
            }
        }];

    });
  
}

- (void)clockInWithModel:(TJTaskModel *)model {
    
    //一个url对应一个 localIdentifier, 如果没查到就下载
    TJUrlDataModel *dataModel = [TJUrlDataModel modelWithUrl:model.videoUrl];
    if (dataModel && dataModel.localIdentifier) { //检查相册里面有没有, 没有就下载
        [TJPhotosTool fetchVideoWithLocalIdentifier:dataModel.localIdentifier completion:^(AVAsset * _Nonnull videoAsset) {
            if (videoAsset) {
                [self sendToDouYin:dataModel.localIdentifier taskModel:model];
            } else {
                [self downloadWithModel:model];
            }
        }];
    } else {//下载
        [self downloadWithModel:model];
    }
}

- (UIImage *)topBackgroundImage {
    return [UIImage imageNamed:@"taskDetail"];
}
 
- (CAShapeLayer *)topShapeLayerWithView:(UIView *)view {
    if (!_topShapeLayer) {
        UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(12, 12)];
        _topShapeLayer = [CAShapeLayer layer];
        _topShapeLayer.path = maskPath.CGPath;
    }
    return _topShapeLayer;
}

- (CAShapeLayer *)bottomShapeLayerWithView:(UIView *)view {
    if (!_bottomShapeLayer) {
        UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight cornerRadii:CGSizeMake(12, 12)];
        _bottomShapeLayer = [CAShapeLayer layer];
        _bottomShapeLayer.path = maskPath.CGPath;
    }
    return _bottomShapeLayer;
}

- (NSMutableArray *)datas {
    if (!_datas) {
        _datas = [NSMutableArray array];
    }
    return _datas;
}

- (void)loadData {
    [TJMinePresent loadTaskDetailWithTaskId:self.model.taskId complete:^(NSArray * _Nonnull datas, NSString *remainTime, NSError * _Nullable error) {
        self.subTitleLabel.text = [NSString stringWithFormat:@"今日剩余打卡次数：%@次", remainTime];
        if (datas.count) {
            [self.datas removeAllObjects];
            [self.datas addObjectsFromArray:datas];
        }
        self.emptyDataHandler.canDisplay = YES;
        [self.tableView reloadData];
    }];
}



@end
